package me.stone.stanimeclient.core.ui.player

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import androidx.media3.ui.DefaultTimeBar
import androidx.media3.ui.TimeBar
import java.util.concurrent.CopyOnWriteArraySet

@OptIn(UnstableApi::class)
class AgePlayerTimeBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    timeBarAttrs: AttributeSet? = null,
    defStyleRes: Int = 0
) : DefaultTimeBar(context, attrs, defStyleAttr, timeBarAttrs, defStyleRes) {

    private var mSeekSing = false

    private var mTempListeners = CopyOnWriteArraySet<TimeBar.OnScrubListener>()

    fun seekBegan() {
        mSeekSing = true
        mTempListeners.forEach {
            removeListener(it)
        }
    }

    fun seekEnded() {
        mTempListeners.forEach {
            addListener(it)
        }
        mSeekSing = false
    }

    fun seekPosition(position: Long) {
        super.setPosition(position)
    }

    override fun addListener(listener: TimeBar.OnScrubListener) {
        super.addListener(listener)
        if (mSeekSing) return
        mTempListeners.add(listener)
    }

    override fun removeListener(listener: TimeBar.OnScrubListener) {
        super.removeListener(listener)
        if (mSeekSing) return
        mTempListeners.remove(listener)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (mSeekSing) return false
        return super.onTouchEvent(event)
    }

    override fun setPosition(position: Long) {
        if (mSeekSing) return
        super.setPosition(position)
    }

}